;$(function () {
    layui.use(['form', 'laydate', 'table', 'element'], function () {
        var table = layui.table,
            form = layui.form,
            laydate = layui.laydate,
            element = layui.element;
        //业务选择跳转
        element.on('nav(menuSelection)', function (elem) {
            // console.log(elem); //得到当前点击的DOM对象
            // alert(this.id)
            if (!isEmpty(this.id)) {
                window.location = "../menu/menuChoose?menuId=" + this.id;
                $("#" + this.id).parent().attr("class", "layui-this");
            }
        });

    });
    //金额格式化
    $("body").on("blur", ".moneyFormatter", function (e) {
        // var obj = event.srcElement ? event.srcElement : event.target;
        var obj = this;
        var rel = /^[0-9]+\.?[0-9]{0,9}$/;//是正数
        if (obj.value != '') {
            if (rel.test(obj.value)) {
                var arr = obj.value.split('.');
                if (arr.length > 1) {
                    arr[1] = arr[1] + '00';
                }
                obj.value = arr[0] + '.' + (arr[1] || '00').substring(0, 2);
            } else {
                $(obj).val('');
                $(obj).focus();
                layer.tips("金额格式有误", $(obj), {
                    tips: [1, '#2B2B2B'],
                    time: 2000
                });
            }
        }
    });
    //折扣格式化
    $("body").on("blur", ".discountFormatter", function (e) {
            var obj = this;
            var rel = /^[0-9]+\.?[0-9]{0,9}$/;//是正数
            var flag = false;
            if (obj.value != '') {
                if (rel.test(obj.value)) {
                    if (parseFloat(obj.value) < 10 && parseFloat(obj.value) >= 0.1) {
                        var arr = obj.value.split('.');
                        if (arr.length > 1) {
                            arr[1] = arr[1] + '0';
                        }
                        obj.value = arr[0] + '.' + (arr[1] || '0').substring(0, 1);
                        flag = true;
                    }
                }
                if (!flag) {
                    $(obj).val('');
                    $(obj).focus();
                    layer.tips("输入格式有误", $(obj), {
                        tips: [1, '#2B2B2B'],
                        time: 2000
                    });
                }
            }
        }
    );
});

Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

//获取当前日期并格式化
function getNowAndFormatDate() {
    // var date = new Date();
    // var seperator1 = "-";
    // var year = date.getFullYear();
    // var month = date.getMonth() + 1;
    // var strDate = date.getDate();
    // if (month >= 1 && month <= 9) {
    //     month = "0" + month;
    // }
    // if (strDate >= 0 && strDate <= 9) {
    //     strDate = "0" + strDate;
    // }
    // var currentdate = year + seperator1 + month + seperator1 + strDate;
    // return currentdate;
    let day = new Date();
    return day.format("yyyy-MM-dd");
}

//获取前一天日期并格式化
function getYesterdayAndFormatDate() {
    let day = new Date();
    day.setDate(day.getDate() - 1);
    return day.format("yyyy-MM-dd");
}//获取近一周日期并格式化
function getWeekAndFormatDate() {
    let day = new Date();
    day.setDate(day.getDate() - 6);
    return day.format("yyyy-MM-dd");
}

function getMouthAndFormatDate() {
    let day = new Date();
    day.setMonth(day.getMonth() - 1);
    return day.format("yyyy-MM-dd");
}

function getYearAndFormatDate() {
    let day = new Date();
    day.setFullYear(day.getFullYear() - 1);
    return day.format("yyyy-MM-dd");
}


function isEmpty(val) {
    // null or undefined
    if (val == null) return true;

    if (typeof val === 'boolean') return false;

    if (typeof val === 'number') return !val;

    if (val instanceof Error) return val.message === '';

    switch (Object.prototype.toString.call(val)) {
        // String or Array
        case '[object String]':
        case '[object Array]':
            return !val.length;

        // Map or Set or File
        case '[object File]':
        case '[object Map]':
        case '[object Set]': {
            return !val.size;
        }
        // Plain Object
        case '[object Object]': {
            return !Object.keys(val).length;
        }
    }

    return false;
}

function changeWaresStatus(obj) {
    layui.use('table', function () {
        var table = layui.table;
        let jsonStr = obj.replace(
            /"?((?:(?!\{).)+?)"?="?((?:(?![\}|,|"]).)*)"?([,|\}])/g,
            (_, b, c, d) => {
                return `"${b.trim()}":"${c.trim()}"${d}`
            },
        );
        let parse = JSON.parse(jsonStr);
        let a = "";
        for (let i = 0; i < parse.length; i++) {
            a += parse[i].id + ","
        }
        a = a.substr(0, a.length - 1);
        $.ajax({
            url: "../wares/changeStatus",
            type: "POST",
            data: {
                "id_str": a
            },
            async: false,
            dataType: "json",
            success: function (data) {
                if (data.code === true) {
                    layer.msg("下架成功");
                } else {
                    layer.msg("操作失败")
                }
                setTimeout("location.reload()", 800);
            }
        });
    });
}

/**
 * 创建动态form表单，为了隐藏路径中的参数
 *
 * @param url 请求路径 如：${pageContext.request.contextPath}/homepageController/homepageUpdata
 * @param method    请求类型，如：POST 或 GET
 * @param jsonData    请求数据（数据为json格式），如： [{aid:55}]
 * @param target    target类型，如：'_blank'在新窗口/选项卡中打开。' _self'在同一框架中打开（默认）。'_parent'在父框架中打开。'_top'在整个窗口中打开。'framename'在指定的 iframe 中打开。
 * @returns
 */
function pageSkipping(url, jsonData) {
    var dlform = document.createElement('form');
    dlform.style = "display:none;";
    dlform.method = "post";
    dlform.action = url;
    dlform.target = "_self";//当前页面打开
    var json = jsonData;
    for (var i = 0, l = json.length; i < l; i++) {
        for (var key in json[i]) {
            var hdnFilePath = document.createElement('input');
            hdnFilePath.type = 'hidden';
            hdnFilePath.name = key;
            hdnFilePath.value = json[i][key];
            dlform.appendChild(hdnFilePath);
        }
    }
    document.body.appendChild(dlform);
    dlform.submit();
    document.body.removeChild(dlform);
}

//当按钮单击时触
// $(function(){
//     $("#updataButton").click(function(){
//         var url = "${pageContext.request.contextPath}/homepageController/homepageUpdata";	//请求路径
//         var type = "POST";	//请求类型
//         var jsonData = [];	//构建json
//         jsonData.push({"commodityid":"36"});	//将传参放入json中
//         var targetType = "_self";	//在当前页面打开
//         pageSkipping(url,type,jsonData,targetType)
//     });
// });

// function tabAdd(id) {
//     if (id != null) {
//         var num = id.replace(/[^\d]/g, '');
//         // $(".mainInterface").css("display", "none");
//         // $("#div" + num).css("display", "block");
//         if (num = 1) {
//             $("#divddd").empty();
//             $("#divddd").load("")
//         }
//     }
// };


